package com.wj.sort;

/**
 * 选择排序
 * @author wen.jie
 * @date 2021/8/4 17:38
 */
public class Selection {

    /**
     * 排序
     * @author wen.jie
     * @date 2021/8/4 17:28
     */
    public static void sort(Comparable<?>[] a) {
        for (int i = 0; i <= a.length - 2; i++) {
            //记录最小元素的索引
            int minIndex = i;
            for (int j = i+1; j< a.length; j++){
                if (greater(a[minIndex], a[j])){
                    minIndex = j;
                }
            }
            exchange(a, i, minIndex);
        }
    }

    /**
     * 比较
     * @author wen.jie
     * @date 2021/8/4 17:18
     */
    private static boolean greater(Comparable v, Comparable w) {
        return v.compareTo(w) > 0;
    }

    /**
     * 交换
     * @author wen.jie
     * @date 2021/8/4 17:27
     */
    private static void exchange(Comparable[] a, int i, int j) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

}
